<template>
  <j-modal
    :title="titleCar"
    :width="width"
    :visible="visible"
    switchFullscreen
    @ok="handleOk"
    :okButtonProps="{ class: { 'jee-hidden': disableSubmit } }"
    @cancel="handleCancel"
    :cancelText="$t('common.table.close')"
  >

    <div id="track-container">
      <div class="query-bar">
        <div class="button-wrapper">
          <a-form-item :style="{ display: 'contents', width: 'calc(50% - 12px)' }">
            <a-date-picker
              v-model="startTime"
              show-time
              placeholder="开始时间"
              style="margin-left: 20px;"
            />

            <a-date-picker
              v-model="endTime"
              show-time
              placeholder="结束时间"
              style="margin-left: 20px;"
            />

          <a-button @click="startTrack" style="margin-left: 20px;">开始</a-button>
          <a-button @click="pauseTrack" style="margin-left: 20px;">暂停</a-button>
          <a-button @click="resumeTrack" style="margin-left: 20px;">继续</a-button>
          <a-button @click="stopTrack" style="margin-left: 20px;">停止</a-button>

            <div style=" text-align: right; font-weight: bold; display: inline; float: right ">
              累计: {{ totalDistance.toFixed(0) }}Km   当次里程:{{ currentDistance.toFixed(2) }}Km  车速:{{ (currentSpeed*0.1).toFixed(2) }}Km/h
            </div>



          </a-form-item>
          <a-form-item :style="{ display: 'block' }">
          <a-slider
            v-model="trackProgress"
            @change="handleTrackProgressChange"
            @input="handleTrackProgressInput"
            :max="path.length - 1"
            :trackStyle="{ backgroundColor: '#ff5733', height: '8px' }"
            :handleStyle="{ borderColor: '#ff5733', backgroundColor: '#ff5733', height: '20px', width: '20px' }"
          />
          </a-form-item>
        </div>
      </div>


      <div class="map-track-container">
      <div id="map"></div>
      <div class="track-body">
        <!-- 添加经纬度显示区域 -->
        <div class="latlng-info" ref="latlngInfoContainer">
          <ul>
            <li
              v-for="(point, index) in path"
              :key="index"
              :class="{ active: trackProgress === index }"
              :ref="'pointItem' + index"
            >
              <span>位置: {{ index + 1 }}</span><br>
              <span>经度: {{ point.lng }}</span><br>
              <span>纬度: {{ point.lat }}</span>
            </li>
          </ul>
        </div>
      </div>
      </div>
    </div>
  </j-modal>
</template>

<script>
import { getAction, postAction } from '@api/manage';
import _ from 'lodash';
import { RecycleScroller } from 'vue-virtual-scroller'
import * as dayjs from 'dayjs'
export default {
  name: "TrackComponent",
  components: {
    RecycleScroller
  },
  props: {
    carCode: {
      type: String,
      required: true,
    },
    plate: {
      type: String,
      required: true,
    },
    titleCar: {
      type: String,
      required: true,
    },
    currentlongitude: {
      type: [String, Number],
      required: true,
    },
    currentlatitude: {
      type: [String, Number],
      required: true,
    },
    visible: {
      type: Boolean,
      default: false,
      required: true,
    },
  },
  data() {
    return {
      title: "",
      width: '90.9%',
      disableSubmit: false,
      sysOrgCode: "",
      regionOptions: [],
      map: null,
      marker: null,
      infoWindow: null,
      polylineLayer: null,
      currentPath:null,
      isF: false, // 标志变量
      trackDataUrl: "/rental/ebike/track-list",
      currentLatLng: null, // 当前经纬度信息
      totalDistance: 0, // 当前总里程数
      currentDistance: 0, // 当前里程数
      currentSpeed: 0, // 当前里程数
      path: [
        { lat: 29.054436187788614, lng: 119.47280534849226 },
        { lat: 29.0545, lng: 119.4729 },
        { lat: 29.0546, lng: 119.473 },
        { lat: 29.0547, lng: 119.4731 },
        { lat: 29.0548, lng: 119.4732 },
      ],
      startTime: null, // 开始时间
      endTime: null, // 结束时间
      trackProgress: 0, // 轨迹进度
      timer: null, // 定时器
      isPlaying: false, // 是否正在播放
      speed: 100, // 每秒移动的距离（米）
    };
  },
  watch: {
    carCode(newVal) {
      if (newVal) {
        //this.getTrackList(newVal);
      }
    },
    visible(newVal) {
      if (newVal) {

        this.getTrackList(this.carCode);
        this.loadScript(() => {
          this.initMap();
        });
      }
    },
    trackProgress(newVal) {

       this.scrollToActiveItem(newVal);
    }
  },
  methods: {
    loadScript(callback) {
      const KEY = window._CONFIG["qqMapKey"];
      const script = document.createElement("script");
      script.type = "text/javascript";
      script.src = `https://map.qq.com/api/gljs?v=1.exp&key=${KEY}&libraries=tools`;
      document.body.appendChild(script);
      script.onload = () => {
        callback && callback();
      };
    },
    handleTrackProgressChange: _.debounce((value)=> {
      // 用户手动拖动进度条结束后，更新地图和列表
      this.updateMarkerPosition(value);
      this.scrollToActiveItem(value);
    }, 200),
    handleTrackProgressInput(value) {
      // 用户在拖动进度条时，只更新地图，不更新列表
      this.updateMarkerPosition(value);
    },
    updateMarkerPosition(index) {
      if (index >= 0 && index < this.path.length) {
        console.log("updateMarkerPosition",this.path)
        const position = this.path[index];
        this.currentLatLng = position;
        this.marker.setGeometries([
          {
            id: 'car',
            styleId: 'car-down',
            position: new TMap.LatLng(position.lat, position.lng),
          },
          // "start" 标记保持在起点位置
          {
            id: "start",
            styleId: "start",
            position: new TMap.LatLng(this.path[0].lat, this.path[0].lng),
          },
          // "end" 标记保持在终点位置
          {
            id: "end",
            styleId: "end",
            position: new TMap.LatLng(
              this.path[this.path.length - 1].lat,
              this.path[this.path.length - 1].lng
            ),
          },
        ]);
         this.map.setCenter(new TMap.LatLng(position.lat, position.lng));
        this.trackProgress = index;
        this.moveMarker(index);
        // 如果正在播放，则继续移动标记
        if (this.isPlaying) {
          //this.moveMarker(index);
        }
      }
    },
    debouncedTrackProgressChange: _.debounce(function(value) {
      this.onTrackProgressChange(value);
    }, 200),
    initMap() {
      console.log("当前经纬度",this.currentLatLng)
      const center = new TMap.LatLng(this.currentlatitude, this.currentlongitude);
      this.map = new TMap.Map("map", {
        zoom: 15,
        center: center,
      });
      this.initMarker();
      this.initPolyline();
    },
    getTrackList(carCode) {
      console.log("getTrackList------------------",carCode, this.startTime, this.endTime);
      let startTime = dayjs(this.startTime).format( 'YYYY-MM-DD HH:mm:ss');
      let endTime = dayjs(this.endTime).format('YYYY-MM-DD HH:mm:ss');
      console.log("getTrackList------------------2",startTime);
      const params = {
        sysOrgCode: this.sysOrgCode,
        carCode: carCode,
        startTime: this.startTime ? startTime : null,
        endTime: this.endTime ? endTime : null,
      };
      console.log("查询参数 ________params____________：" + params);
      postAction(this.trackDataUrl, params).then((res) => {
        if (res.success) {
          console.log("vehicleList的值" + res.result);
          this.path = JSON.parse(res.result);
          this.updateMap();
        }
      });
    },
    getTrackListT(carCode) {
      console.log("getTrackList------------------", carCode, this.startTime, this.endTime);
      let startTime = dayjs(this.startTime).format('YYYY-MM-DD HH:mm:ss');
      let endTime = dayjs(this.endTime).format('YYYY-MM-DD HH:mm:ss');
      console.log("getTrackList------------------2", startTime);
      const params = {
        sysOrgCode: this.sysOrgCode,
        carCode: carCode,
        startTime: this.startTime ? startTime : null,
        endTime: this.endTime ? endTime : null,
      };
      console.log("查询参数 ________params____________：" + params);
      // 返回 postAction 的 Promise
      return postAction(this.trackDataUrl, params)
        .then((res) => {
          if (res.success) {
            console.log("vehicleList的值" + res.result);
            this.path= JSON.parse(res.result);
            return  this.path; // 解析并返回轨迹数据
          } else {
            return Promise.reject(new Error(res.message)); // 返回被拒绝的 Promise
          }
        })
        .catch((error) => {
          console.error("获取轨迹数据失败:", error);
          return Promise.reject(error); // 返回被拒绝的 Promise
        });
    },
    updateMap() {
      if (!this.path.length) {
        console.error("updateMap: path is empty.");
        return;
      }

      console.log("updateMap--------------定位信息：", this.path[0].lat, this.path[0].lng);
      if (this.polylineLayer) {
        this.polylineLayer.setGeometries([
          {
            id: "erasePath",
            styleId: "style_blue",
            paths: this.path.map((p) => new TMap.LatLng(p.lat, p.lng)),
          },
        ]);
      }
      if (this.marker) {
        console.log("查询数据库后的PATH",this.path[0].lat, this.path[0].lng);
        this.marker.setGeometries([
          {
            id: "car",
            styleId: "car-down",
            position: new TMap.LatLng(this.path[0].lat, this.path[0].lng),
          },
          {
            id: "start",
            styleId: "start",
            position: new TMap.LatLng(this.path[0].lat, this.path[0].lng),
          },
          {
            id: "end",
            styleId: "end",
            position: new TMap.LatLng(
              this.path[this.path.length - 1].lat,
              this.path[this.path.length - 1].lng
            ),
          },
        ]);
      }
    },
    initPolyline() {
      if (!this.path.length) {
        console.error("initPolyline: path is empty.");
        return;
      }
      this.polylineLayer = new TMap.MultiPolyline({
        map: this.map,
        styles: {
          style_blue: new TMap.PolylineStyle({
            color: "#3777FF",
            width: 4,
            borderWidth: 2,
            borderColor: "#FFF",
            lineCap: "round",
            eraseColor: "rgba(190,188,188,1)",
          }),
        },
        geometries: [
          {
            id: "erasePath",
            styleId: "style_blue",
            paths: this.path.map((p) => new TMap.LatLng(p.lat, p.lng)),
          },
        ],
      });
    },
    initMarker() {
      console.log("initMarker,--------------initMarker------------- 定位信息：", this.path[0].lat, this.path[0].lng);
      this.marker = new TMap.MultiMarker({
        map: this.map,
        styles: {
          "car-down": new TMap.MarkerStyle({
            width: 40,
            height: 40,
            anchor: { x: 20, y: 20 },
            faceTo: "map",
            rotate: 180,
            src: "/vehicle.png",
          }),
          start: new TMap.MarkerStyle({
            width: 25,
            height: 35,
            anchor: { x: 16, y: 32 },
            src: "https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/start.png",
          }),
          end: new TMap.MarkerStyle({
            width: 25,
            height: 35,
            anchor: { x: 16, y: 32 },
            src: "https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/end.png",
          }),
        },
        geometries: [
          {
            id: "car",
            styleId: "car-down",
            position: new TMap.LatLng(this.currentlatitude, this.currentlongitude),
          },
          /*{
            id: "start",
            styleId: "start",
            position: new TMap.LatLng(this.path[0].lat, this.path[0].lng),
          },
          {
            id: "end",
            styleId: "end",
            position: new TMap.LatLng(
              this.path[this.path.length - 1].lat,
              this.path[this.path.length - 1].lng
            ),
          },*/
        ],
      });

      if (!this.path.length) {
        console.error("initMarker: path is empty.");
        return;
      }

      this.marker.add([{
        id: "start",
        styleId: "start",
        position: new TMap.LatLng(this.path[0].lat, this.path[0].lng),
      },
        {
          id: "end",
          styleId: "end",
          position: new TMap.LatLng(
            this.path[this.path.length - 1].lat,
            this.path[this.path.length - 1].lng
          ),
        }
      ])

      this.marker.on("click", (e) => {
        if (e.geometry.id === "car") {
          this.infoWindow.setPosition(e.geometry.position);
          this.infoWindow.open();
        }
      });

      this.marker.on("moving", (e) => {
        const passedLatLngs = e.car && e.car.passedLatLngs;
        if (passedLatLngs) {
          this.polylineLayer.eraseTo(
            "erasePath",
            passedLatLngs.length - 1,
            passedLatLngs[passedLatLngs.length - 1]
          );
        }
      });

      this.infoWindow = new TMap.InfoWindow({
        map: this.map,
        position: new TMap.LatLng(this.path[0].lat, this.path[0].lng),
        offset: { x: 0, y: -30 },
        content: "<div>轨迹详情</div>",
      });
    },
    startTrack() {
      console.log(this.carCode);
      this.getTrackListT(this.carCode).then(path => {
        if (!path.length) {
          console.error("startTrack: path is empty.");
          return;
        }
        this.path = path;
        this.updateMap();
        if (this.currentPath!=null){
          this.marker.updateGeometries([
            {
              id: "car",
              styleId: "car-down",
              position: this.currentPath,
            },
          ]);
        }else {
          this.marker.updateGeometries([
            {
              id: "car",
              styleId: "car-down",
              position: new TMap.LatLng(this.path[0].lat, this.path[0].lng),
            },
          ]);
        }
        console.log("开始轨迹后的PATH",this.path[0].lat, this.path[0].lng)
        this.map.setCenter(new TMap.LatLng(this.path[0].lat, this.path[0].lng));
        this.marker.stopMove();
        clearInterval(this.timer); // 清除 timer
        this.trackProgress = 0;
        const totalDistance = this.calculateTotalDistance(this.path);
        const duration = (totalDistance / this.speed) * 1000; // 持续时间（毫秒）
        this.moveMarker(this.trackProgress, duration);

      });
    },
    moveMarker(startIndex, duration) {
      const remainingPath = this.path.slice(startIndex);
      console.log("moveMarker的PATH",this.path[0].lat, this.path[0].lng)
      const remainingDistance = this.calculateTotalDistance(remainingPath);
      const remainingDuration = (remainingDistance / this.speed) * 1000;
      this.marker.moveAlong(
        {
          car: {
            path: remainingPath.map((p) => new TMap.LatLng(p.lat, p.lng)),
            duration: remainingDuration, // 使用剩余持续时间
          },
        },
        {
          autoRotation: true,
        }
      );

      this.startProgressUpdate(remainingDuration, startIndex);
    },
    startProgressUpdate(duration, startIndex) {
      clearInterval(this.timer);
      let currentIndex = startIndex;
      let startTime = Date.now(); // 记录开始时间

      this.timer = setInterval(() => {
        if (currentIndex < this.path.length - 1) {
          // 计算已经过的时间比例
          const elapsedTimeRatio = (Date.now() - startTime) / duration;

          // 根据时间比例更新当前索引
          currentIndex = Math.floor((this.path.length - startIndex - 1) * elapsedTimeRatio) + startIndex;
          if (currentIndex >= this.path.length - 1) {
            currentIndex = this.path.length - 1; // 确保不超出边界
          }

          this.trackProgress = currentIndex;
          this.currentLatLng = this.path[currentIndex]; // 更新当前经纬度信息
          this.currentDistance = this.path[currentIndex].mil - this.path[0].mil;
          this.totalDistance = this.path[currentIndex].mil;
          this.currentSpeed = this.path[currentIndex].speed;
        } else {
          clearInterval(this.timer);
        }
      }, 20); // 可以根据需要调整间隔时间，但应小于移动的总时间
    },

    calculateTotalDistance(path) {
      let totalDistance = 0;
      for (let i = 1; i < path.length; i++) {
        totalDistance += this.calculateDistance(path[i - 1], path[i]);
      }
      return totalDistance;
    },
    calculateDistance(point1, point2) {
      const radLat1 = (point1.lat * Math.PI) / 180.0;
      const radLat2 = (point2.lat * Math.PI) / 180.0;
      const a = radLat1 - radLat2;
      const b = ((point1.lng - point2.lng) * Math.PI) / 180.0;
      const s =
        2 *
        Math.asin(
          Math.sqrt(
            Math.pow(Math.sin(a / 2), 2) +
            Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)
          )
        );
      return s * 6378137; // 地球半径（米）
    },
    onTrackProgressChange(value) {
      const position = this.path[value];
      if (position) {
        clearInterval(this.timer); // 停止轨迹播放
        this.currentLatLng = position; // 更新当前经纬度信息
        this.marker.updateGeometries([
          {
            id: "car",
            styleId: "car-down",
            position: new TMap.LatLng(position.lat, position.lng),
          },
        ]);
        this.map.setCenter(new TMap.LatLng(position.lat, position.lng));
        this.marker.stopMove();
        this.trackProgress = value;
        if (this.isPlaying) {
          this.moveMarker(value, (this.calculateTotalDistance(this.path.slice(value)) / this.speed) * 1000);
        }

        this.scrollToActiveItem(value);
      }
    },
    scrollToActiveItem(index) {
      this.$nextTick(() => {
        const activeItems = this.$refs["pointItem" + index];
        console.log(activeItems, "activeItems==================");
        if (activeItems && activeItems.length > 0) {
          const activeItem = activeItems[0];
          const container = this.$refs.latlngInfoContainer;
          console.log(container, "container==================");
          if (container && activeItem) {
            container.scrollTop = activeItem.offsetTop - container.offsetTop;
          }
        }
      });
    },
    pauseTrack() {
      this.marker.pauseMove();
      clearInterval(this.timer); // 暂停进度更新
      this.isPlaying = false;
    },
    resumeTrack() {
      this.marker.resumeMove();
      console.log("resumeTrack ===========轨迹进度==============trackProgress",this.trackProgress);
      const remainingDuration = (this.calculateTotalDistance(this.path.slice(this.trackProgress)) / this.speed) * 1000;
      this.startProgressUpdate(remainingDuration, this.trackProgress);
      this.isPlaying = true;
    },
    stopTrack() {
      this.marker.stopMove();
      clearInterval(this.timer); // 停止进度更新
      this.trackProgress = 0;
      this.isPlaying = false;
    },
    handleOk() {
      this.$emit("ok");
    },
    handleCancel() {
      this.$emit("cancel");
      this.isF = false;
    },
  },
};
</script>

<style scoped>
#track-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.button-wrapper {
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.map-track-container {
  display: flex;
  flex: 1;
  height: 1000px;
}

#map {
  flex: 30;
  height: 100%;
  border-right: 1px solid #ddd;
}

.track-body {
  flex: 5;
  height: 100%;
  padding: 10px;
  background-color: #fff;
}

.latlng-info {
  overflow-y: auto;
  padding: 10px;
}

.latlng-info ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

.latlng-info li {
  padding: 10px;
  border-bottom: 1px solid #ddd;
}

.latlng-info li.active {
  background-color: #ffeb3b;
  font-weight: bold;
}
.latlng-info {
  max-height: 400px; /* 固定高度 */
  overflow-y: auto;
  padding: 10px;
}

.latlng-info ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

.latlng-info li {
  padding: 10px;
  border-bottom: 1px solid #ddd;
}

.latlng-info li.active {
  background-color: #ffeb3b;
  font-weight: bold;
}.latlng-info {
   max-height: 550px; /* 固定高度 */
   overflow-y: auto;
   padding: 10px;
   display: flex;
   flex-direction: column;
 }

.latlng-info ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
  position: relative;
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center; /* 使 ul 的子元素居中对齐 */
}

.latlng-info ul:before {
  content: '';
  display: block;
  height: 50%; /* 占据 ul 高度的一半 */
}

.latlng-info ul:after {
  content: '';
  display: block;
  height: 50%; /* 占据 ul 高度的一半 */
}

.latlng-info li {
  padding: 10px;
  border-bottom: 1px solid #ddd;
  position: relative; /* 确保 li 定位相对于 ul */
}

.latlng-info li.active {
  background-color: #ffeb3b;
  font-weight: bold;
}


</style>